package com.qf.electronic.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.electronic.dto.UserDto;
import com.qf.electronic.dto.UserStateDto;
import com.qf.electronic.pojo.Menu;
import com.qf.electronic.pojo.User;
import com.qf.electronic.mapper.UserMapper;
import com.qf.electronic.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.electronic.vo.UserVo;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wu
 * @since 2023-05-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    //支持账号登录、邮箱登录、手机号登录
    @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED)
    @Override
    public User loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = this.baseMapper.getUserBy(username);
        if(user == null) throw new UsernameNotFoundException("登录账号不存在");
        if(user.getState() == 0) throw new DisabledException("账号被冻结");
        return user;
    }

    @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED)
    @Override
    public List<Menu> getUserMenus(String username) {
        return this.baseMapper.getUserMenus(username);
    }

    @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED)
    @Override
    public Page<UserVo> getUsers(UserDto userDto) {
        Page<UserVo> page = new Page<>(userDto.getCurrentPage(), userDto.getPageSize());
        return this.baseMapper.getUsers(page, userDto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean changeUserState(UserStateDto stateDto) {
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.set("state", stateDto.getState());
        wrapper.in("username", stateDto.getUsernames());
        return update(wrapper);
    }

    @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED)
    @Override
    public List<User> getExportUsers(Map<String, Object> params, int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        return this.baseMapper.getExportUsers(params, offset, pageSize);
    }

    @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED)
    @Override
    public long getExportUserCount(Map<String, Object> params) {
        return this.baseMapper.getExportUserCount(params);
    }
}
